package com.hbx.service.impl;

import com.hbx.constant.CachePrefixContent;
import com.hbx.service.AdminService;
import com.hbx.utils.CacheUtils;
import com.hbx.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/*
 * @Project:resource-sharing-platform-java
 * @Author:hbx
 * 
 * */
@Service
@Slf4j
public class AdminServiceImpl implements AdminService {

    @Autowired
    private CacheUtils cacheUtils;

    /**
     * 新增敏感词
     * @param sensitive
     * @param result
     */
    @Override
    public void addSensitive(String sensitive, Result<String> result) {
        Long r = cacheUtils.add(CachePrefixContent.PLAT_SENSITIVE_THESAURUS, new Object[]{sensitive});
        if (null != r && r == 1L) {
            result.setCode(200).setMsg("敏感词添加成功!");
            return;
        }
        if (null != r && r == 0L) {
            result.setCode(201).setMsg("敏感词添加失败, 敏感词已存在!");
            return;
        }
        result.setCode(201).setMsg("操作失败");
    }

    /**
     * 移除敏感词
     * @param sensitive
     * @param result
     */
    @Override
    public void removeSensitive(String sensitive, Result<String> result) {
        Long r = cacheUtils.setRemove(CachePrefixContent.PLAT_SENSITIVE_THESAURUS, new Object[]{sensitive});
        if (null != r && r == 1L) {
            result.setCode(200).setMsg("敏感词移除成功");
            return;
        }
        if (null != r && r == 0L) {
            result.setCode(201).setMsg("敏感词移除失败, 敏感词不存在!");
            return;
        }
        result.setCode(201).setMsg("敏感词移除失败");
    }

    /**
     * 获取敏感词列表
     * @param result
     */
    @Override
    public void getSensitiveList(Result<List<String>> result) {
        Set<Object> members = cacheUtils.getSetMembers(CachePrefixContent.PLAT_SENSITIVE_THESAURUS);
        List<String> data = CollectionUtils.isEmpty(members) ? new ArrayList<>() :
                members.stream().map(m -> m.toString()).collect(Collectors.toList());
        result.setCode(200).setData(data);
    }
}
